package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.StatusConstant;
import com.ruoyi.system.domain.DomainEntity;
import com.ruoyi.system.service.DomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Anonymous
@Controller
@RequestMapping("domain")
public class AppDomainPageController {

    @Autowired
    private DomainService domainService;

    @GetMapping("/page/error")
    public String error() {
        return "error";
    }

    @GetMapping("/page/{domain}")
    public ModelAndView domainPage(@PathVariable String domain, HttpServletResponse response) throws Exception {
        if(domain.isEmpty()){
            throw new Exception("未找到主域名");
        }

        DomainEntity domainEntity = domainService.queryByDomain(domain);
        // 校验主域名状态
        int domainStatus = domainEntity.getStatus();
        if(domainStatus == StatusConstant.DISABLE){
            // 主域名未开启，直接跳到错误页面
            return new ModelAndView("redirect:error");
        }

        List<DomainEntity> domainList = domainService.queryDomainListByParentId(domainEntity.getId());
        List<DomainEntity> filterSubDomains = null;
        if(!domainList.isEmpty()){
            filterSubDomains = domainList.stream().filter(e -> e.getStatus() == StatusConstant.ENABLE).collect(Collectors.toList());
        }
        // shuffle 打乱顺序
        Collections.shuffle(filterSubDomains);
        DomainEntity subDomain = filterSubDomains.get(0);

        if(subDomain!=null){
            List<DomainEntity> landingPages = domainService.queryDomainListByParentId(subDomain.getId());
            List<DomainEntity> filterPages = null;
            if(!landingPages.isEmpty()){
                filterPages = landingPages.stream().filter(e -> e.getStatus() == StatusConstant.ENABLE).collect(Collectors.toList());
            }
            // shuffle 打乱顺序
            Collections.shuffle(filterPages);
            DomainEntity landingPageLink = filterPages.get(0);
            return new ModelAndView(new RedirectView(landingPageLink.getDomain()));

        }
        return new ModelAndView("redirect:error");
    }


    @GetMapping("/luodi/{index}")
    public ModelAndView luodiPage(@PathVariable String index) throws Exception {
        if(index.isEmpty()){
            throw new Exception("");
        }
        return new ModelAndView(new RedirectView("http://baidu.com"));
    }

}
